package com.sensePlusVR.manager;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.RequestParams;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.bean.ActorItem;
import com.sensePlusVR.net.NetCallBack;
import com.sensePlusVR.net.NetRequestManager;
import com.sensePlusVR.net.RequestUtils;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.ConstantURL;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;


@SuppressWarnings("deprecation")
public class ActorManager extends BaseManager{
	private String TAG = ActorManager.class.getSimpleName();
	public static int EventActorAllGot = 0;
	public static int EventActorIdsGot = 1;
	
	private static ActorManager INSTANTS;
	
	static public ActorManager getInstants(){
		if (INSTANTS == null){
			INSTANTS = new ActorManager();
		}
		return INSTANTS;
	}
	
	private void updateDb(List<ActorItem> list){
		for (ActorItem item:list){
			save(item);
		}
	}
	
	public void save(ActorItem item){
		ActorItem.saveOrUpdate(item);
	}
	
	public List<ActorItem> getAllActors(boolean force){
		List<ActorItem> list = ActorItem.getAllActors(0, 100);
		if (list == null || list.size() == 0 || force){
			MyLog.d(TAG, "getAllActors list == null");
			list = null;
			DownloadTask task = new DownloadTask();
			task.start();
		}else{
			MyLog.d(TAG, "getAllActors list size ： " + list.size());
		}
		return list;
	}
	
	public ActorItem getActorById(int actorId){
		return ActorItem.getActorById(actorId);
	}
	
	public ActorItem getActorByName(String name){
		return ActorItem.getActorByName(name);
	}
	
	public List<ActorItem> getFollowActors(List<Integer> ids){
		List<Integer> newIds = new ArrayList<Integer>();
		if (ids != null && ids.size() > 0){
			for(Integer id : ids){
				ActorItem aItem = ActorItem.getActorById(id);
				if(aItem != null && ActorItem.isRealActor(aItem)){
					newIds.add(id);
				}
			}
			List<ActorItem> list = ActorItem.getActorListByIds(newIds);
			if (list != null && list.size() > 0){
				MyLog.d(TAG, "getFollowActors list size ： " + list.size());
				return list;
			}else {
				MyLog.d(TAG, "getFollowActors list == null");
				DownloadTask task = new DownloadTask(newIds);
				task.start();
			}
		}
		return null;
	}
	

	
	public class DownloadTask{
		private List<Integer> ids;
		private boolean doAll;
		public DownloadTask(List<Integer> ids){
			this.ids = ids;
			doAll = false;
		}
		public DownloadTask(){
			doAll = true;
		}
		
		public void start(){
			if (doAll)
				startAll();
			else
				startByIds();
		}
		private void startAll(){
			RequestParams params = new RequestParams();
			params.put("currentpage", 0);
			params.put("pagesize", 100);
			params.put("type", Constant.TYPE_REAL);
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token getAllFollowGameList : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			
			final String url = ConstantURL.ACTOR_LIST;
			
			RequestUtils.clientTokenGet(VRApplication.getAppContext(),url, params, new NetCallBack(){
				@Override
				public void onMySuccess(int statusCode, Header[] aheader, JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					MyLog.d(TAG, "getAllFollowGameList onMySuccess statusCode : "
							+ statusCode);
					if(jsonobject == null){
						MyLog.d(TAG, "getAllFollowGameList jsonobject == null");
						return;
					}
					MyLog.d(TAG, "getAllFollowGameList onMySuccess jsonobject : "
							+ jsonobject.toString());
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] headers, JSONArray response) {
					super.onMySuccess(statusCode, headers, response);
					MyLog.d(TAG, "getAllFollowGameList onMySuccess statusCode : "
							+ statusCode);
					if(response == null){
						MyLog.d(TAG, "getAllFollowGameList response == null");
						return;
					}
					MyLog.d(TAG, "getAllFollowGameList onMySuccess response : "
							+ response.toString());
					if (statusCode == 200) {
						MyLog.d(TAG, "getAllFollowGameList success");
						List<ActorItem> aiList = JSON.parseArray(response.toString(), ActorItem.class);
						if(aiList != null && aiList.size() > 0){
							//NotifyUser2(aiList);
							updateDb(aiList);
							callEventListener(EventActorAllGot, aiList);
							MyLog.d(TAG, "getAllFollowGameList giList size : " + aiList.size());
							MyLog.d(TAG, "getAllFollowGameList giList : " + aiList.toString());
							
						}
					}
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					MyLog.e(TAG, "getAllFollowGameList onMyFailure statusCode : "
							+ statusCode);
					if(errorResponse == null){
						MyLog.e(TAG, "getAllFollowGameList onMyFailure errorResponse == null");
						return;
					}
					MyLog.e(TAG, "getAllFollowGameList onMyFailure errorResponse : "
							+ errorResponse.toString());
				}
			});
		}

		private void startByIds() {
			if(ids == null || ids.size() == 0)
				return;
			MyLog.d(TAG, "getMyFollowGameList collectionList : " + ids.toString());
			String json = JSON.toJSONString(ids);
			MyLog.d(TAG, "getMyFollowGameList json : " + json);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token getMyFollowGameList : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			
			final String url =  ConstantURL.ACTOR_LIST_BY_IDS;
			MyLog.d(TAG, "getMyFollowGameList url : " + url);
			
			RequestUtils.clientTokenPost(VRApplication.getAppContext(), url, new ByteArrayEntity(json.getBytes()), Constant.STR_APPLICATION_JSON, new NetCallBack(){
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					MyLog.d(TAG, "getMyFollowGameList onMySuccess statusCode : "
							+ statusCode);
					if(jsonobject == null){
						MyLog.d(TAG, "getMyFollowGameList jsonobject == null");
						return;
					}
					MyLog.d(TAG, "getMyFollowGameList onMySuccess jsonobject : "
							+ jsonobject.toString());
					
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] headers,
						JSONArray response) {
					super.onMySuccess(statusCode, headers, response);
					MyLog.d(TAG, "getMyFollowGameList onMySuccess statusCode : "
							+ statusCode);
					if(response == null){
						MyLog.d(TAG, "getMyFollowGameList response == null");
						return;
					}
					MyLog.d(TAG, "getMyFollowGameList onMySuccess response : "
							+ response.toString());
					if (statusCode == 200) {
						MyLog.d(TAG, "getMyFollowGameList success");
						List<ActorItem> actorList = JSON.parseArray(response.toString(), ActorItem.class);
						if(actorList != null && actorList.size() > 0){
							//NotifyUser(actorList, 1);
							updateDb(actorList);
							callEventListener(EventActorIdsGot, actorList);
							MyLog.d(TAG, "getMyFollowGameList giList size : " + actorList.size());
							//MyLog.d(TAG, "getMyFollowGameList giList : " + actorList.toString());
						}
					}
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONArray errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					MyLog.e(TAG, "getMyFollowGameList onMyFailure statusCode : "
							+ statusCode);
					if(errorResponse == null){
						MyLog.e(TAG, "getMyFollowGameList onMyFailure errorResponse == null");
						return;
					}
					MyLog.e(TAG, "getMyFollowGameList onMyFailure errorResponse : "
							+ errorResponse.toString());
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext(),url);
				}
			});
		}

	}

}
